package com.anivia.controller;

import com.anivia.entity.Env;
import com.anivia.entity.Info;
import com.anivia.entity.Project;
import com.anivia.mapper.EnvMapper;
import com.anivia.service.EnvService;
import com.anivia.service.InfoService;
import com.anivia.service.ProjectService;
import com.anivia.vo.ProjectVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author wangj
 * @date Created in 2020-09-03
 */
@RestController
public class IndexController {

    @Autowired
    private EnvService envService;
    @Autowired
    private InfoService infoService;
    @Autowired
    private ProjectService projectService;

    @GetMapping("/index")
    public Map<String, Object> index() {
        Map<String, Object> map = new HashMap<>(16);
        List<Project> list = projectService.list();
        List<ProjectVo> returnList = new ArrayList<>();
        list.forEach(p -> {
            ProjectVo projectVo = new ProjectVo();
            BeanUtils.copyProperties(p, projectVo);

            QueryWrapper<Info> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().groupBy(Info::getEnvId).eq(Info::getProjectId, p.getId()).select(Info::getEnvId);
            List<Integer> envIds = infoService.list(queryWrapper).stream().map(Info::getEnvId).collect(Collectors.toList());

            if(envIds.size()>0){
                QueryWrapper<Env> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.lambda().in( Env::getId, envIds).orderByAsc(Env::getId);
                List<Env> envs = envService.list(queryWrapper1);
                projectVo.setEnv(envs);
            }
            QueryWrapper<Info> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.lambda().eq(Info::getProjectId, p.getId());
            List<Info> infoList = infoService.list(queryWrapper2);
            projectVo.setInfos(infoList);

            returnList.add(projectVo);
        });
        map.put("projects", returnList);
        return map;
    }
}